package teach.aistar.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import teach.aistar.model.entity.Chat;
import teach.aistar.model.entity.User;
import teach.aistar.model.entity.UserDetail;
import teach.aistar.service.IChatService;
import teach.aistar.service.IUserDetailService;
import teach.aistar.service.IUserService;

import javax.persistence.criteria.CriteriaBuilder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/chat")
public class ChatController {

    @Autowired
    private IChatService iChatService;

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IUserDetailService iUserDetailService;

    @GetMapping("/getText")
    public String getText(HttpServletRequest request, HttpSession session){
        return "chat";
    }

    @GetMapping("/searchText")
    public String serachText(HttpServletRequest request, HttpSession session) throws Exception {
        int textType=Integer.parseInt(request.getParameter("text_type"));
        List<Chat> chats=iChatService.selectByType(textType);
        request.setAttribute("chats",chats);

        User user= (User) session.getAttribute("User");

        if(user == null){
            throw new Exception("请先登录！");
        }
//        UserDetail userDetail=iUserDetailService.selectById(user.getUId());
        User user1 = iUserService.getByUsername(user.getUname());
        request.setAttribute("user",user1);
        request.setAttribute("time",new Date());
        return "chat";
    }

    @GetMapping("/sendText")
    public String sendText(HttpServletRequest request, HttpSession session) {
        String uname  =  request.getParameter("uname");
        int chatType= Integer.parseInt(request.getParameter("chatType"));
        String chatText=request.getParameter("chatText");

        Chat chat=new Chat();
        chat.setChatType(chatType);
        chat.setChatPerson(uname);
        chat.setChatText(chatText);
        chat.setChatTime(new Date());
        iChatService.insert(chat);

        List<Chat> chats=iChatService.selectByType(chatType);
        request.setAttribute("chats",chats);
        User user= (User) session.getAttribute("User");
        User user2 = iUserService.getByUsername(user.getUname());
//        UserDetail userDetail=iUserDetailService.selectById(user.getUId());
        request.setAttribute("user",user2);
        request.setAttribute("time",new Date());
        return  "chat";
    }
}
